package com.guodaxia.gzh.service.user;

import com.guodaxia.gzh.common.AccessToken;
import com.guodaxia.gzh.util.HttpUtil;
import com.guodaxia.gzh.util.JSONUtil;
import com.guodaxia.gzh.util.SpringContextUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author guojianquan
 * @date 2024/12/12 0:17
 */
public interface IWXTokenService {

    String APP_ID = "appid";

    String APP_SECRET = "secret";

    String GRANT_TYPE = "grant_type";


    String APP_TOKEN = "token";

    //获取token
    default String getWXToken() throws Exception {
        RedisTemplate redisTemplate = (RedisTemplate) SpringContextUtils.getBean("RedisTemplate");

        String token = (String) redisTemplate.opsForValue().get(APP_TOKEN);
        if (token != null && !token.isEmpty()) {
            return token;
        }
        synchronized (APP_TOKEN) {
            token = (String) redisTemplate.opsForValue().get(APP_TOKEN);
            if (token != null && !token.isEmpty()) {
                return token;
            }
            String tokenRes = HttpUtil.http("https://api.weixin.qq.com/cgi-bin/token", HttpMethod.GET, getReqParams(), null);
            AccessToken accessToken = JSONUtil.toObject(tokenRes, AccessToken.class);
            if (accessToken.access_token != null && !accessToken.access_token.isEmpty()) {
                redisTemplate.opsForValue().set(APP_TOKEN, accessToken.access_token, 2, TimeUnit.HOURS);
                return accessToken.access_token;
            } else {
                throw new Exception(String.format("获取微信公众号token错误,错误代码:[%s],错误消息:[%s]", accessToken.getErrcode(), accessToken.getErrmsg()));
            }
        }
    }


    default HashMap getReqParams() {
        AppInfo appInfo = (AppInfo) this.getAppInfo();
        HashMap<Object, Object> paramMap = new HashMap<>();
        paramMap.put(APP_ID, appInfo.APP_ID);
        paramMap.put(APP_SECRET, appInfo.APP_SECRET);
        paramMap.put(GRANT_TYPE, appInfo.GRANT_TYPE);
        return paramMap;
    }

    AppBaseInfo getAppInfo();
}
